<?php
/**
 * BugFree is free software under the terms of the FreeBSD License.
 *
 * list bugs.
 *
 * @link        http://www.bugfree.org.cn
 * @package     BugFree
 */
/* Init BugFree system. */
require('Include/Init.inc.php');
require('Include/FuncImportOutport.php');
@ini_set('memory_limit', -1);

/* Local APIs */
function GetReviewMultiInfo($ReviewID)
{
		//Set the $ReviewID to the Session Variable
		if($ReviewID)
		{
				$_SESSION['CurrentReviewID'] = $ReviewID;
		}
		else
		{
				$ReviewID = $_SESSION['CurrentReviewID'];
		}
		Rainy_Debug($ReviewID,__FUNCTION__,__LINE__,__FILE__,1);
		
		//Get Raw ReviewInfo from DataBase
		$Columns = '*';
		$ReviewInfo = dbGetRow('ReviewInfo',$Columns,"ReviewID = '{$ReviewID}' AND {$_SESSION[TestUserACLSQL]} AND IsDroped = '0'");
		if(!$ReviewInfo['ReviewID'])
		{
    	sysErrorMsg();
		}
	
    /* Set ReviewInfo MultiInfo */
    //Get OriginalChangeTitle
    if(!empty($ReviewInfo['ChangeID']))	
    {
        $ChangeInfo = dbGetRow('ChangeInfo',$Columns,"ChangeID = '{$ReviewInfo['ChangeID']}' AND {$_SESSION[TestUserACLSQL]}");
        $ReviewInfo['ChangeTitle'] = $ChangeInfo['ChangeTitle'];
    }
		//Set $_SESSION['ReviewOrderBy']
    if(empty($_SESSION['ReviewOrderBy']))
    {
        $_SESSION['ReviewOrderBy']['OrderBy'] = ' ReviewID DESC';
        $_SESSION['ReviewOrderBy']['OrderByColumn'] = 'ReviewID';
        $_SESSION['ReviewOrderBy']['OrderByType'] = 'DESC';
    }

		//Get The ReviewIDList with the ReviewQueryCondition 
    $WhereStr = "{$_SESSION['TestUserACLSQL']} AND {$_SESSION['ReviewQueryCondition']}";
    if('ReviewID' == $_SESSION['ReviewOrderBy']['OrderByColumn'])
    {
        $OrderByStr = "{$_SESSION['ReviewOrderBy']['OrderByColumn']} {$_SESSION['ReviewOrderBy']['OrderByType']}";
    }
    else
    {
        $OrderByStr = "{$_SESSION['ReviewOrderBy']['OrderByColumn']} {$_SESSION['ReviewOrderBy']['OrderByType']},ReviewID ASC";
    }
    $ReviewIdInfoList = dbGetList('ReviewInfo','ReviewID',$WhereStr,'',$OrderByStr,'');
    $PreNextIdArr = getPreNextId($ReviewIdInfoList,'ReviewID',$ReviewID);
    $PreReviewID = $PreNextIdArr[0];
    $NextReviewID = $PreNextIdArr[1];

		//Get the UserList of Project
    $UserList = testGetProjectUserNameList($ReviewInfo['ProjectID']);
    $ReviewInfo = testSetReviewMultiInfo($ReviewInfo, $UserList);

    $ReviewActionList = testGetActionAndFileList('Review', $ReviewInfo['ReviewID']);
    $LastActionID = testGetLastActionID('Review',$ReviewInfo['ReviewID']);
    $ReviewInfo['ActionList'] = $ReviewActionList['ActionList'];
    $ReviewInfo['FileList'] = $ReviewActionList['FileList'];
    $ReviewInfo['ReviewIDList'] = getBugTitleArr($ReviewInfo['ReviewID']);
    return $ReviewInfo;
}

//Get the ReviewID and ActionType From Request Variables
$ReviewID = $_REQUEST['ReviewID'];
if($ReviewID > 0)
{
	$_SESSION['ReviewID'] = $ReviewID;
}
else
{
	$ReviewID = $_SESSION['ReviewID'];
}

$ActionType = $_REQUEST['ActionType'];

//Set the Query Fields
$ReviewInfo = GetReviewMultiInfo($ReviewID);
$TPL->assign('ReviewID', $ReviewID);
$TPL->assign('ActionType', $ActionType);
$TPL->assign('ReviewInfo', $ReviewInfo);

//Query Was triggered by Project Select
$ProjectID = testGetCurrentProjectId();
if($_GET['ProjectID'] - 0 > 0)
{
		Rainy_Debug("ProjectID",__FUNCTION__,__LINE__,__FILE__);
    $_SESSION['ReviewCommentQueryCondition'] = "ProjectID = '{$_GET['ProjectID']}'";
}

//Query was triggered by Module Select
if($_GET['ModuleID'] - 0 > 0)
{
		Rainy_Debug("ModuleID",__FUNCTION__,__LINE__,__FILE__);
    $_SESSION['TestCurrentModuleID'] = $_GET['ModuleID'];
    $_SESSION['ReviewCommentQueryCondition'] = "ModuleID IN ({$_GET['ChildModuleIDs']})";
}

//Query was triggered by PostQuery
if($_POST['PostQuery'])
{
    Rainy_Debug("PostQuery",__FUNCTION__,__LINE__,__FILE__);
    $QueryStr = baseGetGroupQueryStr($_POST);
    $_SESSION['ReviewCommentQueryCondition'] = $QueryStr;
    $_SESSION['ReviewCommentQueryTitle'] = '';
    $_SESSION['ReviewCommentAndOrListCondition'] = baseGetAndOrListStr($_POST);
    $_SESSION['ReviewCommentFieldListCondition'] = baseGetFieldListStr($_POST);
    $_SESSION['ReviewCommentOperatorListCondition'] = baseGetOperatorListStr($_POST);
    $_SESSION['ReviewCommentValueListCondition'] = baseGetValueListStr($_POST);
    $_SESSION['ReviewCommentLeftParenthesesListCondition'] = baseGetLeftParentheseListStr($_POST);
    $_SESSION['ReviewCommentRightParenthesesListCondition'] = baseGetRightParentheseListStr($_POST);
}

//Query was triggered by Saved Query Condition
if($_REQUEST['QueryID'])
{
		Rainy_Debug("QueryID",__FUNCTION__,__LINE__,__FILE__);
    $QueryInfo = dbGetRow('TestUserQuery', '', "QueryID='{$_REQUEST[QueryID]}' AND QueryType='ReviewComment'");
    $_SESSION['ReviewCommentQueryCondition'] = $QueryInfo['QueryString'];
    $_SESSION['ReviewCommentQueryTitle'] = $QueryInfo['QueryTitle'];
    $_SESSION['ReviewCommentAndOrListCondition'] = unserialize($QueryInfo['AndOrList']);
    $_SESSION['ReviewCommentFieldListCondition'] = unserialize($QueryInfo['FieldList']);
    $_SESSION['ReviewCommentOperatorListCondition'] = unserialize($QueryInfo['OperatorList']);
    $_SESSION['ReviewCommentValueListCondition'] = unserialize($QueryInfo['ValueList']);
    $_SESSION['ReviewCommentFieldsToShow'] = $QueryInfo['FieldsToShow'];
    $_SESSION['ReviewCommentLeftParenthesesListCondition'] = unserialize($QueryInfo['LeftParentheses']);
    $_SESSION['ReviewCommentRightParenthesesListCondition'] = unserialize($QueryInfo['RightParentheses']);
}
else
{
   $_REQUEST['QueryID'] = '-1';
}

//Set WHERE String
$WHERE = array();
$URL = array();

$WHERE[] = "ReviewID={$ReviewID}";

if($_SESSION['ReviewCommentQueryCondition'] != '')
{
    $WHERE[] = $_SESSION['ReviewCommentQueryCondition'];
}

Rainy_Debug($WHERE,__FUNCTION__,__LINE__,__FILE__);

//Query was triggered by OrderBy Click
if($_GET['OrderBy'])
{
		Rainy_Debug("OrderBy",__FUNCTION__,__LINE__,__FILE__);
    $OrderByList = explode('|', $_GET['OrderBy']);
    $OrderByColumn = $OrderByList[0];
    $OrderByType = $OrderByList[1];
    $OrderBy = join(' ', $OrderByList);
    $URL[] = 'OrderBy=' . $_GET['OrderBy'];
    $_SESSION['ReviewCommentOrderBy']['OrderBy'] = $OrderBy;
    $_SESSION['ReviewCommentOrderBy']['OrderByColumn'] = $OrderByColumn;
    $_SESSION['ReviewCommentOrderBy']['OrderByType'] = $OrderByType;
}
else
{
    if(empty($_SESSION['ReviewCommentOrderBy']))
    {
        $_SESSION['ReviewCommentOrderBy']['OrderBy'] = ' ReviewCommentID DESC';
        $_SESSION['ReviewCommentOrderBy']['OrderByColumn'] = 'ReviewCommentID';
        $_SESSION['ReviewCommentOrderBy']['OrderByType'] = 'DESC';
    }
    $OrderBy = $_SESSION['ReviewCommentOrderBy']['OrderBy'];
    $OrderByColumn = $_SESSION['ReviewCommentOrderBy']['OrderByColumn'];
    $OrderByType = $_SESSION['ReviewCommentOrderBy']['OrderByType'];
}

//QueryMode
if($_GET['QueryMode'])
{
		Rainy_Debug("QueryMode",__FUNCTION__,__LINE__,__FILE__);
    $hasCustomField = false;
    $_SESSION['hasReviewCommentCustomField'] = false;
    $QueryModeList = explode('|', $_GET['QueryMode']);
    $QueryColumn = $QueryModeList[0];
    $QueryValue = $QueryModeList[1];
    $WHERE = array();
    $WHERE[] = $_SESSION['TestUserACLSQL'];
    $QueryCondition = "";
    if(preg_match('/date/i', $QueryColumn))
    {
        $QueryCondition =  $QueryColumn . ' ' . sysStrToDateSql($QueryValue);
    }
    else
    {
        $QueryCondition = "{$QueryColumn}='{$QueryValue}'";
    }
    $_SESSION['ReviewCommentQueryCondition'] = $QueryCondition;
    $_SESSION['ReviewCommentQueryColumn'] = $QueryColumn;
    $WHERE[] = $QueryCondition;
    $URL[] = 'QueryMode=' . sysStripSlash($_GET['QueryMode']);
    // check if is set custom field for special function
    if(!array_key_exists($QueryColumn, $_LANG['ReviewCommentQueryField']))
    {
        $hasCustomField = $_SESSION['hasReviewCommentCustomField'] = true;
    }
}

$Url = '?' . join('&', $URL);
$WHERE[] = "IsDroped = '0'";
$Where = join(' AND ', $WHERE);

Rainy_Debug($Url,__FUNCTION__,__LINE__,__FILE__);
Rainy_Debug($Where,__FUNCTION__,__LINE__,__FILE__);

$FieldsToShow = testSetCustomFields('ReviewComment', $ProjectID, $hasCustomField);
if(!array_key_exists($OrderByColumn, $FieldsToShow))
{
    $OrderBy = 'ReviewCommentID DESC';
    $OrderByColumn = 'ReviewCommentID';
    $OrderByType = 'DESC';
}

/* Get pagination */
$Pagination = new Page('ReviewCommentInfo', '', '', '', 'WHERE ' . $Where . ' ORDER BY ' . $OrderBy, $Url, $MyDB);
$LimitNum = $Pagination->LimitNum();
$TPL->assign('PaginationDetailInfo', $Pagination->getDetailInfo());
$ColumnArray = @array_keys($FieldsToShow);
$Columns = 'ReviewCommentID,ReviewCommentStatus,' . join(',',$ColumnArray);


$OrderColumnList = $ColumnArray;
$OrderByTypeList = array();
foreach($OrderColumnList as $OrderColumn)
{
    if($OrderColumn == $OrderByColumn)
    {
        $OrderByTypeList[$OrderColumn] = $OrderTypeReverseArray[$OrderByType];
    }
    else
    {
        $OrderByTypeList[$OrderColumn] = $OrderByType;
    }
}

//ReviewCommentList的导入处理代码
if($_FILES['file']['error']==2)	//导入成功
{
      sysObFlushJs("alert('{$_LANG['ImportFileExceed']}');");
}
elseif($_FILES['file']['error']==0)
{
        if($_FILES['file']['tmp_name'])   // 如果文件存在则进行批量导入
        {
	  				$findtype=strtolower(strrchr($_FILES['file']['name'],"."));

          	if($findtype!='.xml')	//文件必须以.xml结尾
          	{
            		sysObFlushJs("alert('{$_LANG['ImportFileSuffixError']}');");
          	}
          	else 
          	{
          			//读取文件内容到FileContents
		  					$file=fopen($_FILES['file']['tmp_name'],"r");
		  					$FileContents = fread($file, filesize($_FILES['file']['tmp_name']));
		  					$FileContents = preg_replace('/<Font.*>|<\/Font>/Us', '', $FileContents);
								//将文件内容解析成变量，并存储在Dom变量中	
		            $Dom =  XML_unserialize($FileContents);
    		        $DomRowArray = $Dom[Workbook][Worksheet][Table][Row];
								//解析DomRowArray 并导入至数据库中
            		ParseImportReviewCommentXML($DomRowArray,$_LANG);
        	}
    		}
}

if($_GET['Export'] == 'HtmlTable')
{
    $Columns = '';
    $LimitNum = '';
}

$ReviewCommentListSql = dbGetListSql(dbGetPrefixTableNames('ReviewCommentInfo'), '', $Where, '', $OrderBy, $LimitNum);
if($Where != $_SESSION['OldReviewCommentQueryWhereStr'])
{
    $_SESSION['OldReviewCommentQueryWhereStr'] = $Where;
    if(!($_GET['QueryMode']))
    {
        $_SESSION['ReviewCommentQueryColumn'] = '';
    }
}

$ReviewCommentList = dbGetListBySql($ReviewCommentListSql);
$UserNameList = testGetOneDimUserList();
$ReviewCommentList = testSetReviewCommentListMultiInfo($ReviewCommentList, $UserNameList);
//print_r($ReviewCommentList);exit; 

$TPL->assign('ReviewCommentList', $ReviewCommentList);

$TPL->assign('OrderByColumn', $OrderByColumn);
$TPL->assign('OrderByType', $OrderByType);
$TPL->assign('QueryMode', $_GET['QueryMode']);
$TPL->assign('QueryColumn', $_SESSION['ReviewCommentQueryColumn']);
$TPL->assign('OrderByTypeList', $OrderByTypeList);
$TPL->assign('BaseTarget', '_self');
$TPL->assign('TestMode', 'ReviewComment');

if($_GET['Export'] == 'HtmlTable')
{
    $TPL->assign('DataList', $ReviewCommentList);
    $TPL->assign('FieldsToShow', $_LANG["ReviewCommentFields"]);
    $TPL->display('ExportList.tpl');
    exit;
}

//ReviewCommentList导出命令处理代码
if($_GET['Export'] == 'XMLFile')  //批量导出ReviewComment
{
   $ReviewCommentExportList = dbGetList('ReviewCommentInfo','', $Where, '', $OrderBy);
   $ReviewCommentCount = sizeof($ReviewCommentExportList);


   if($ReviewCommentCount >5000 ){
     sysObFlushJs("alert('{$_LANG['ExportCountExceed']}');");
   }
   else{
       $ReviewCommentExportColumnMust = array('ReviewCommentID' , 'ReviewCommentTitle', 'ProjectName', 'ModulePath', 'ReproSteps'); //必须包含的字段

      $ReviewCommentExportColumnArray = $ColumnArray;
      foreach($ReviewCommentExportColumnMust as $Item)
      {
         if(!in_array($Item, $ReviewCommentExportColumnArray))
            $ReviewCommentExportColumnArray[] = $Item;

      }

      $URL=$_CFG['File']['UploadDirectory'] . "/reviewcommentlist.xml";
      $File = fopen($URL,"w");

      $Content = ExportXML($ReviewCommentExportList,$ReviewCommentExportColumnArray,$_LANG['ReviewCommentFields']);

      file_put_contents($URL, $Content);
      header('Content-type: text/xml; charset=utf-8');
      header('Content-Disposition: attachment; filename=buglist.xml');
      readfile($URL);
      exit;
   }
}
$TPL->assign('TestIsAdmin', $_SESSION['TestIsAdmin']);
$TPL->assign('QueryID', $_REQUEST['QueryID']);
$TPL->assign('QueryTitle', $_SESSION['ReviewCommentQueryTitle'] );
$TPL->display('ReviewCommentList1.tpl');
?>